<template>
  <div>
    <Breadcrumb></Breadcrumb>
    <el-card>
      <el-alert
        show-icon
        title="注意：只允许为第三级分类设置相关参数"
        type="warning"
      >
      </el-alert>
      <!-- 选择商品分类选择框 -->
      <el-row class="cat_opt">
        <el-col>
          <span>选择商品分类：</span>
          <el-cascader
            v-model="selectedKeys"
            :options="catelist"
            :props="{
              expandTrigger: 'hover',
              value: 'cat_id',
              label: 'cat_name',
              children: 'children',
            }"
            @change="handleChanged"
            clearable
          ></el-cascader>
        </el-col>
      </el-row>
      <el-tabs v-model="activeName" @tab-click="handleTabClick">
        <el-tab-pane label="动态参数" name="many">
          <el-button
            type="primary"
            size="mini"
            :disabled="isBtnDisabled"
            @click="showDialog"
            >添加参数</el-button
          >
          <el-table :data="manyTableData" border stripe>
            <el-table-column type="expand">
              <template slot-scope="scope">
                <el-tag
                  v-for="(item, i) in scope.row.attr_vals"
                  :key="i"
                  closable
                  @close="handleClose(i, scope.row)"
                  >{{ item }}</el-tag
                >
                <el-input
                  class="input-new-tag"
                  v-if="scope.row.inputVisible"
                  v-model="scope.row.inputValue"
                  ref="saveTagInput"
                  size="small"
                  @keyup.enter.native="handleInputConfirm(scope.row)"
                  @blur="handleInputConfirm(scope.row)"
                >
                </el-input>
                <el-button
                  v-else
                  class="button-new-tag"
                  size="small"
                  @click="showInput(scope.row)"
                  >+ New Tag</el-button
                >
              </template>
            </el-table-column>
            <el-table-column type="index" label="#"></el-table-column>
            <el-table-column
              label="参数名称"
              prop="attr_name"
            ></el-table-column>
            <el-table-column label="操作">
              <template slot-scope="scope">
                <el-button
                  type="primary"
                  icon="el-icon-edit"
                  size="mini"
                  @click="showEditDialog(scope.row)"
                  >编辑</el-button
                >
                <el-button
                  type="warning"
                  icon="el-icon-delete"
                  size="mini"
                  @click="deleteCate(scope.row)"
                  >删除</el-button
                >
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
        <el-tab-pane label="静态属性" name="only"
          ><el-button
            type="primary"
            size="mini"
            :disabled="isBtnDisabled"
            @click="showDialog"
            >添加属性</el-button
          >
          <el-table :data="onlyTableData" border stripe>
            <el-table-column type="expand">
              <template slot-scope="scope">
                <el-tag
                  v-for="(item, i) in scope.row.attr_vals"
                  :key="i"
                  closable
                  @close="handleClose(i, scope.row)"
                  >{{ item }}</el-tag
                >
                <el-input
                  class="input-new-tag"
                  v-if="scope.row.inputVisible"
                  v-model="scope.row.inputValue"
                  ref="saveTagInput"
                  size="small"
                  @keyup.enter.native="handleInputConfirm(scope.row)"
                  @blur="handleInputConfirm(scope.row)"
                >
                </el-input>
                <el-button
                  v-else
                  class="button-new-tag"
                  size="small"
                  @click="showInput(scope.row)"
                  >+ New Tag</el-button
                >
              </template>
            </el-table-column>
            <el-table-column type="index" label="#"></el-table-column>
            <el-table-column
              label="参数名称"
              prop="attr_name"
            ></el-table-column>
            <el-table-column label="操作">
              <template slot-scope="scope">
                <el-button
                  type="primary"
                  icon="el-icon-edit"
                  size="mini"
                  @click="showEditDialog(scope.row)"
                  >编辑</el-button
                >
                <el-button
                  type="warning"
                  icon="el-icon-delete"
                  size="mini"
                  @click="deleteCate(scope.row)"
                  >删除</el-button
                >
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
      </el-tabs>
    </el-card>
    <addDialog ref="addDialogRef" @getParamsData="getParamsData"></addDialog>
    <editDialog ref="editDialogRef" @getParamsData="getParamsData"></editDialog>
  </div>
</template>

<script>
import addDialog from './addDialog/Dialog.vue'
import editDialog from './editDialog/editDialog.vue'
export default {
  data() {
    return {
      catelist: [],
      selectedKeys: [],
      //被激活的页签的名称
      activeName: 'many',
      manyTableData: [],
      onlyTableData: [],
      inputVisible: false,
      inputValue: '',
    }
  },
  components: {
    addDialog,
    editDialog,
  },
  created() {
    this.getCateList()
  },
  methods: {
    async getCateList() {
      const { data: res } = await this.$http.get('categories')
      if (res.meta.status !== 200) {
        return this.$message.error('获取商品分类数据失败')
      }
      this.catelist = res.data
    },
    //监听级联选择器
    handleChanged() {
      this.getParamsData()
    },
    //获取分类参数数据
    async getParamsData() {
      if (this.selectedKeys.length !== 3) {
        this.selectedKeys = []
        this.manyTableData = []
        this.onlyTableData = []
        return
      }
      const { data: res } = await this.$http.get(
        `categories/${this.cateId}/attributes`,
        { params: { sel: this.activeName } }
      )
      if (res.meta.status !== 200) {
        return this.$message.error('获取数据失败')
      }
      res.data.forEach((item) => {
        item.attr_vals = item.attr_vals ? item.attr_vals.split(',') : []
        this.$set(item, 'inputVisible', false)
        this.$set(item, 'inputValue', '')
      })
      if (this.activeName === 'many') {
        this.manyTableData = res.data
      } else {
        this.onlyTableData = res.data
      }
    },
    //监听Tab页签点击事件
    handleTabClick() {
      this.getParamsData()
    },
    titleText() {
      if (this.activeName === 'many') {
        return '动态参数'
      } else {
        return '静态属性'
      }
    },
    showDialog() {
      this.$refs.addDialogRef.dialogVisible = true
      this.$refs.addDialogRef.titleText = this.titleText()
      this.$refs.addDialogRef.cateId = this.cateId
      this.$refs.addDialogRef.activeName = this.activeName
    },
    showEditDialog(data) {
      this.$refs.editDialogRef.dialogVisible = true
      this.$refs.editDialogRef.titleText = this.titleText()
      this.$refs.editDialogRef.cateId = this.cateId
      this.$refs.editDialogRef.activeName = this.activeName
      this.$refs.editDialogRef.editForm = data
    },
    async deleteCate(data) {
      console.log(data)
      const confirmResult = await this.$confirm(
        '此操作将永久删除该数据, 是否继续?',
        '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
        }
      ).catch((err) => err)
      //如果用户点击确认，返回为字符串 confirm 取消则为cancel，可以使用elementui原生方法，
      // 原生返回的是promise，所以可以用异步优化
      if (confirmResult != 'confirm') {
        return this.$message.info('已取消删除')
      }
      const { data: res } = await this.$http.delete(
        `categories/${this.cateId}/attributes/${data.attr_id}`
      )
      if (res.meta.status !== 200) {
        return this.$message.error('删除数据失败！')
      }
      this.$message.success('删除数据成功！')
      this.getParamsData()
    },
    async handleInputConfirm(data) {
      if (data.inputValue.trim().length === 9) {
        data.inputValue = ''
        data.inputVisible = false
        retrun
      }
      data.attr_vals.push(data.inputValue.trim())
      data.inputValue = ''
      data.inputVisible = false
      this.saveAttrVals(data)
    },
    showInput(data) {
      data.inputVisible = true
      //文本框获取焦点
      //nextTick 方法是保证页面上元素被重新渲染后，才能指定回调函数中的代码
      this.$nextTick((_) => {
        this.$refs.saveTagInput.$refs.input.focus()
      })
    },
    handleClose(i, row) {
      row.attr_vals.splice(i, 1)
      this.saveAttrVals(row)
    },
    async saveAttrVals(data) {
      const { data: res } = await this.$http.put(
        `categories/${this.cateId}/attributes/${data.attr_id}`,
        {
          attr_name: data.attr_name,
          attr_sel: data.attr_sel,
          attr_vals: data.attr_vals.join(','),
        }
      )
      if (res.meta.status !== 200) {
        return this.$message.error('修改失败！')
      }
      this.$message.success('修改数据成功！')
      this.getParamsData()
    },
  },
  computed: {
    isBtnDisabled() {
      return this.selectedKeys.length !== 3 ? true : false
    },
    //当前选择的三级分类id
    cateId() {
      if (this.selectedKeys.length == 3) {
        return this.selectedKeys[2]
      }
      return null
    },
  },
}
</script>

<style lang="less" scoped>
.cat_opt {
  margin: 15px 0;
}
.el-cascader {
  width: 30%;
}
.el-tag {
  margin: 10px;
}
.input-new-tag {
  width: 120px;
}
</style>